﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Text.RegularExpressions;

using Fuse8.ContentManagementFramework.Web.ApplicationRuntime;

namespace Fuse8.ContentManagementFramework.Web.MvcPowered
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
    public class StrongPasswordAttribute : ValidationAttribute
    {
        public string PasswordRegex
        {
            get
            {
                var membershipService = new CmsMembershipService();

                return membershipService.PasswordRegex;
            }
        }

        public StrongPasswordAttribute()
        {
            ErrorMessage = "Passwords should be at least 7 characters, comprised of a mix of upper and lower case characters, numbers and special characters.";
        }

        public override bool IsValid(object value)
        {
            bool result = false;

            string str = Convert.ToString(value, CultureInfo.InvariantCulture);
            if (string.IsNullOrEmpty(str))
            {
                result = true;
            }
            else
            {
                var regex = new Regex(PasswordRegex);

                Match match = regex.Match(str);

                result = match.Success;
            }

            return result;
        }
    }
}